<!DOCTYPE html>
<html>
    <head>
        <title>收货地址修改格式</title>
        <link rel="stylesheet" href="../static/css/ej.css">
        <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body style="background-color:#fffbf6">
        {% include 'top_bar.html' %}
        <h2>快团团订单文本</h2>

        <h4>商品</h4>
        <select id="proSel" onchange="generateSpecList();fillPreTxt();"></select>
        <h4>规格</h4>
        <select id="specSel" onchange="fillPreTxt();"></select>
        <!-- <h4>数量</h4>
        <div><input id="qty" type="number" min="0" step="1" value="1" style="width:30px;"></div> -->
        <h4>前接内容：</h4>
        <div><input id="pre_txt" style="height:30px;width:300px;"></div>

        <h4>后接内容：</h4>
        <div><input id="post_txt" style="height:30px;width:300px;">
        </div>

        <div><h4>输入收货人信息：</h4>
        <div><textarea id='txt_input' style="height:150px;width:300px;"></textarea></div>
        
        <hr>
        <div><button id="submit" onclick="dealText()">生成发送格式的文本</button></div>
        <div id='copyBtn' style="margin-top:10px;margin-bottom:10px;display: none;">
            <button id="copy" onclick="copyText()">复制文本</button>
            <div id="resultBox" ><textarea id="result" style="color: #a9474b;width: 300px;height:400px;"></textarea></div>
        </div>
        
        



    <script src="../static/js/common.js"></script>
    <script>
        let pageCfg;
        document.addEventListener('DOMContentLoaded',function(){      
            fetch('/get_ktt_html_page_config')
            .then(response=>response.json())
            .then(dat=>{
                if(dat['res']==='ok'){
                    const data=dat['data']
                    pageCfg=data;
                    console.log(data)
                    const postTxt=document.getElementById('post_txt');
                    postTxt.value=data['后接内容']
                    generateProList(data['商品信息']);
                }
            })
            .catch(error => console.error('Error:', error));     


        });



        function generateProList(proList){
            const proSel=document.getElementById('proSel');
            const specSel=document.getElementById('specSel');
            Object.keys(proList).forEach(item=>{
                const opt=document.createElement('option');
                opt.value=item;
                opt.text=item;
                proSel.appendChild(opt);
            });
            // console.log(proSel.value)
            Object.keys(proList).forEach(key=>{
                if(proSel.value===key){
                    proList[key]['规格'].forEach(item=>{
                        const opt=document.createElement('option');
                        opt.value=`【${item}】`;
                        opt.text=`${item}`;
                        specSel.appendChild(opt);
                    });
                }
            });
            fillPreTxt();
        }

        function generateSpecList(){
            // console.log(pageCfg);
            const proSel=document.getElementById('proSel');
            const specSel=document.getElementById('specSel');
            specSel.innerHTML='';
            Object.keys(pageCfg['商品信息']).forEach(key=>{
                if(proSel.value===key){
                    pageCfg['商品信息'][key]['规格'].forEach(item=>{
                        const opt=document.createElement('option');
                        opt.value=item;
                        opt.text=item;
                        specSel.appendChild(opt);
                    });
                }
            });
            
        }

        function fillPreTxt(){
            const proSel=document.getElementById('proSel');
            const specSel=document.getElementById('specSel');
            const qty=document.getElementById('qty');
            const preTxt=document.getElementById('pre_txt');
            preTxt.value=`${proSel.value} ${specSel.value}`;
        }

        function copyText(){
            const resultBox = document.getElementById('result');
            const postText=document.getElementById('post_txt').value;
            let textToCopy = resultBox.value; // 获取要复制的文本内容

            //js处理换行符，确保正确换行
            const regex = new RegExp(`${postText}`, 'g');
            textToCopy=textToCopy.replace(regex, `${postText}\n`);

            // 创建一个临时的textarea元素
            // const tempTextarea = document.createElement('textarea');

            // tempTextarea.value = textToCopy;
            // document.body.appendChild(tempTextarea);

            // 选中文本并执行复制操作
            resultBox.select();
            document.execCommand('copy');

            // 移除临时的textarea元素
            // document.body.removeChild(tempTextarea);

            // alert('已复制到剪贴板');
        }

        function addLineNumbersAndTexts(text) {
            const preTxt=document.getElementById('pre_txt').value;
            const postText=document.getElementById('post_txt').value;
            const lines = text.split('\n');
            let numberedText = '';
            for (let i = 0; i < lines.length; i++) {
                numberedText += `${i + 1}. ${preTxt} 【${lines[i].split(/,|，/)[1]}件】 ${lines[i].split(/,|，/)[0]} ${postText}\n`;
            }
            return numberedText.trim();
        }

   

        function dealText(){
            const postText=document.getElementById('post_txt').value;
            const txtInput=document.getElementById('txt_input').value;
            const resultBox=document.getElementById('result');
            const preTxt=document.getElementById('pre_txt').value;
            
            

            // 判断是否是多个联系人段落的格式
            const isMultipleContacts = txtInput.includes('联系人');
            
            let formattedResult;
            let  numberedText;
            if(txtInput){
            if (isMultipleContacts) {
                // 使用正则表达式匹配每段联系人信息，并处理格式
                let result = txtInput.replace(/联系人\n\n([\s\S]+?)\n\n联系电话\n\n([\s\S]+?)\n\n详细地址\n\n([\s\S]+?)(?=\n\n联系人|$)/g, function(match, name, phone, address) {
                    return `${name.trim()} ${phone.trim()} ${address.trim()}`;
                });

                result=result.replace(/(^\n+|\n+$)/g,'');
                result=result.trim();

                
                // 将每段末尾的换行符替换为空字符串
                formattedResult = result.replace(/\n$/gm, '');
                numberedText=addLineNumbersAndTexts(formattedResult);
            } else {
                // 如果不是多个联系人段落的格式，直接追加发货人信息
                let lines = txtInput.split('\n');
                lines = lines.filter(element => element !== "");
                const formattedLines = lines.map(line => `${line.trim()}`);
                formattedResult = formattedLines.join('\n');
                formattedResult=formattedResult.replace(/(^\n+|\n+$)/g,'');
                formattedResult=formattedResult.trim();
                numberedText=addLineNumbersAndTexts(formattedResult);




            }

            // 使用 textContent 或 innerText 来设置 <div> 元素的文本内容           

            resultBox.value=numberedText;
            // resultBox.innerText=formattedResult;

            // resultBox.classList.add('result');
            }

            // console.log(result);
            const copyBtn=document.getElementById('copyBtn');
            if(txtInput){
                copyBtn.style.display='block';
            }
            



        }
    </script>
    </body>